var express = require('express');
var router = express.Router();
const WebSocket = require('ws');
const http = require('http');
const querystring = require('querystring');
const multer = require('multer'); // 用于处理文件上传
const server = http.createServer();
const wss = new WebSocket.Server({ server });


const { userModel, messageModel, storeModel } = require('../model/model');

// 获取用户联系的商家
router.get('/stores', async (req, res) => {
  const { id } = req.query;
  const data = await userModel.findOne({ _id: id });
  res.send({
    code: 200,
    data: data.messageStore
  })
})

// 获取商家信息
router.get('/storeInfo', async (req, res) => {
  const { id } = req.query;
  const data = await storeModel.findOne({ _id: id });
  res.send({
    code: 200,
    data
  })
})


// 获取用户信息
router.get('/userInfo', async (req, res) => {
  const { id } = req.query;
  const data = await userModel.findOne({ _id: id });

  res.send({
    code: 200,
    data
  })
})


router.get('/message', async (req, res) => {
  const { userId, recipientId, page, pageSize } = req.query;
  let data = await messageModel.find({
    senderId: { $in: [userId, recipientId] },
    recipientId: { $in: [userId, recipientId] }
  }).sort({ time: 1 });
  const total = data.length;

  let sumPage = Math.ceil(total / pageSize);

  data = data.slice((sumPage - page) * pageSize, (sumPage - page + 1) * pageSize);
  console.log(page);

  res.send({
    code: 200,
    data,
    sumPage
  })
})

// 将消息存储在数据库中
async function add(userId, content, recipientId, type) {
  await messageModel.create({ senderId: userId, content, recipientId, time: Date.now(), type });
}



// 配置 multer 中间件来处理文件上传
const storage = multer.diskStorage({
  // 设置图片存储的位置
  destination: (req, file, cb) => { cb(null, 'upload/'); },
  // 设置图片的名字
  filename: (req, file, cb) => { cb(null, file.fieldname + '-' + Date.now() + ".jpg"); },
});

const upload = multer({ storage });

//post 图片上传
router.post('/imgUpload', upload.single('image'), (request, response) => {
  const data = {
    message: '图片上传成功!',
    //图片的地址
    url: `http://172.20.10.6:3000/upload/${request.file.filename}`
  }
  response.status(200).send(data)
})



const clients = new Map(); // 用于存储客户端连接的Map  

wss.on('connection', (ws, req) => {

  // 用户ID
  let userId = req.url.split('userId=')[1];
  userId = querystring.unescape(userId);

  if (!userId) {
    ws.send('User ID is required');
    ws.close();
    return;
  }

  // 将WebSocket连接与用户ID关联  
  clients.set(userId, ws);

  ws.on('message', (message) => {
    // 解析消息，这里消息格式为 { recipientId: 'xxx', content: 'yyy' }    
    const { recipientId, content, type } = JSON.parse(message);

    // 查找发送者的WebSocket连接  
    const sendUser = clients.get(userId);
    // 心跳机制响应
    if (content === 'ping') {
      sendUser.send(JSON.stringify({ senderId: userId, content: "pong", type }));
      return;
    }
    // 将信息存储到数据库
    add(userId, content, recipientId, type);
    // 发送消息给发送者
    sendUser.send(JSON.stringify({ senderId: userId, content, type }));

    // 查找接收者的WebSocket连接  
    const recipientWs = clients.get(recipientId);
    if (recipientWs) {
      // 发送消息给接收者  
      recipientWs.send(JSON.stringify({ senderId: userId, content, type }));
    } else {
      // 如果接收者不在线，可以选择存储消息、发送通知等  
      console.log(`Recipient ${recipientId} is not online`);
    }
  });

  ws.on('close', () => {
    // 当连接关闭时，从Map中移除  
    clients.delete(userId);
    console.log(`Client with user ID ${userId} disconnected`);
  });

  console.log(`Client with user ID ${userId} connected`);
});

server.listen(8000, '0.0.0.0', () => {
  console.log('WebSocket server is running on ws://localhost:' + 8000 + '/?userId=xxx');
});



module.exports = router;
